package com.mti.zhpt.context;

import com.mti.zhpt.service.BaseService;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @company 上海道枢信息科技-->
 * @anthor created by zhangmingxin
 * @date 2019/8/6
 * @change
 * @describe 获取bean容器
 **/
@Component
public class WebApplicationContext implements ApplicationContextAware {
    private ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 根据名称获取Bean
     * @param name name
     * @return bean
     */
    public Object getBeanByName(String name){
        if(this.context!=null){
            Object object = this.context.getBean(name);
            if(object instanceof BaseService)
                return object;
        }
        return null;
    }

    /**
     * 通过名称和type获取bean
     * @param name bean
     * @param cls type
     * @return bean
     */
    public Object getByNameAndType(String name,Class cls){
        if(this.context!=null){
            Object object = this.context.getBean(name,cls);
            if(object instanceof BaseService)
                return object;
        }
        return null;
    }
}
